import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Delete,
  Query,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { HouseService } from './house.service';
import { CreateHouseDto } from './dto/create-house.dto';
import { CreateHousesBatchDto } from './dto/create-houses-batch.dto';

@Controller('houses')
export class HouseController {
  constructor(private readonly houseService: HouseService) {}

  @Post()
  @HttpCode(HttpStatus.CREATED)
  async create(@Body() createHouseDto: CreateHouseDto) {
    const house = await this.houseService.create(createHouseDto);
    return {
      success: true,
      message: '房屋数据创建成功',
      data: house,
    };
  }

  @Post('batch')
  @HttpCode(HttpStatus.CREATED)
  async createBatch(@Body() createHousesBatchDto: CreateHousesBatchDto) {
    const houses = await this.houseService.createBatch(createHousesBatchDto.houses);
    return {
      success: true,
      message: `批量创建了 ${houses.length} 条房屋数据`,
      data: {
        count: houses.length,
        houses: houses,
      },
    };
  }

  @Get()
  async findAll() {
    const houses = await this.houseService.findAll();
    return {
      success: true,
      data: houses,
      count: houses.length,
    };
  }

  @Get('count')
  async count() {
    const count = await this.houseService.count();
    return {
      success: true,
      data: { count },
    };
  }

  @Get('time-range')
  async findByTimeRange(
    @Query('startTime') startTime: string,
    @Query('endTime') endTime: string,
  ) {
    const start = parseInt(startTime);
    const end = parseInt(endTime);
    const houses = await this.houseService.findByTimeRange(start, end);
    return {
      success: true,
      data: houses,
      count: houses.length,
    };
  }

  @Get(':id')
  async findOne(@Param('id') id: string) {
    const house = await this.houseService.findById(id);
    if (!house) {
      return {
        success: false,
        message: '未找到对应的房屋数据',
      };
    }
    return {
      success: true,
      data: house,
    };
  }

  @Delete(':id')
  @HttpCode(HttpStatus.OK)
  async remove(@Param('id') id: string) {
    const house = await this.houseService.deleteById(id);
    if (!house) {
      return {
        success: false,
        message: '未找到对应的房屋数据',
      };
    }
    return {
      success: true,
      message: '房屋数据删除成功',
      data: house,
    };
  }
}